# -*- coding: utf8 -*-
"""This is for a simple login page for GeoTree demo.
The admin page requires administrator credentials (set in app.yaml).
(For localhost this separation may be not necessary.)
"""

__author__ = 'Artem Dudarev'
__licence__ = 'Apache 2.0'
__date__ = 'Mon 15 Mar 2010 10:03:46 AM EET'

from django.utils import simplejson as json
import logging

from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.api import memcache
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api.labs import taskqueue

from geotree.geotree import GeoTree
from models import OSMPOI


class AdminHandler(webapp.RequestHandler):

    # number of points to add to db
    _BATCH_ADD_SIZE = 50
    # how many tiles are updated per update call
    _BATCH_UPDATE_SIZE = 10
    
    def get(self,action=None):
        self.response.out.write('Admin page<br/><br/>')
        self.response.out.write('<a href="/">Home</a><br/>')
        self.response.out.write('<a href="/_ah/admin">App Engine localhost admin</a><br/>')
        self.response.out.write('<a href="/admin/add_points">Add points to GeoTree</a><br/>')
        self.response.out.write('<a href="/admin/update_tiles">Update GeoTree tiles</a><br/><br/>')

        if action:
            if action == 'add_points':
                batch = OSMPOI.all().filter('is_in_tree =',False).fetch(self._BATCH_ADD_SIZE)
                if batch:
                    GeoTree.insert_points_list(batch, max_z=17, gt_key_name="osm")
                    self.response.out.write('\n\nInfo: added %d points' % len(batch))
                    for p in batch:
                        p.is_in_tree = True
                    db.put(batch)
                    taskqueue.add(url='/admin/add_points', method='GET')
                else:
                    if GeoTree.exists(gt_key_name="osm"):
                        self.response.out.write('\n\nInfo: no POIs to add.')
                        taskqueue.add(url='/admin/update_tiles', method='GET')
                    else:
                        self.response.out.write('\n\nInfo: GeoTree does not exist.')
            if action == 'update_tiles':
                message = GeoTree.update_tiles(count=self._BATCH_UPDATE_SIZE, gt_key_name="osm")
                self.response.out.write('<br/>'+message)
                if not 'nothing to update' in message:
                    taskqueue.add(url='/admin/update_tiles', method='GET')
            # memcaching is not used at the moment
            if action == 'clear_cache':
                memcache.flush_all()
                self.response.out.write('<br/>All memcache entries are deleted.')
    
    
logging.getLogger().setLevel(logging.DEBUG)
application = webapp.WSGIApplication([
                                    ('/admin', AdminHandler),
                                    ('/admin/(.*)', AdminHandler),
                                    ],
                                   debug=True)
                                   # debug=False)

def main():
    run_wsgi_app(application)

if __name__ == '__main__':
    main()
